package com.test.utils;

import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.event.Level;

/**
 * @author kang
 * @Description 简单日志工具
 * @Date 2021/6/16
 */
public class LogWorker {

    private Logger LOGGER;

    private String prefix;

    private final static String OPEN = "[";

    private final static String SEP = "-";

    private final static String CLOSE = "]";

    private LogWorker() {
    }

    public static LogWorker of(Class<?> clazz) {
        return of(clazz, null);
    }

    public static LogWorker of(Class<?> clazz, String prefix) {
        LogWorker logWorker = new LogWorker();
        logWorker.LOGGER = LoggerFactory.getLogger(clazz);
        logWorker.prefix = prefix == null ? null : prefix + SEP;
        return logWorker;
    }

    public void log(String message, Object... param) {
        log(Level.INFO, message, param);
    }

    public void log(Level level, String message, Object... param) {
        log(null, level, message, param);
    }

    public void log(Object requestId, String message, Object... param) {
        log(requestId, Level.INFO, message, param);
    }

    public void log(Object requestId, Level level, String message, Object... param) {
        message = StringUtils.joinWith(null, OPEN, prefix, requestId, CLOSE, message);
        LoggerEnum.valueOf(level.name()).handler.process(LOGGER, message, param);
    }

    @AllArgsConstructor
    public enum LoggerEnum {

        TRACE((l, m, p) -> {
            if (l.isTraceEnabled()){
                l.trace(m, p);
            }
        }),
        DEBUG((l, m, p) -> {
            if (l.isDebugEnabled()){
                l.debug(m, p);
            }
        }),
        INFO((l, m, p) -> {
            if (l.isInfoEnabled()){
                l.info(m, p);
            }
        }),
        WARN((l, m, p) -> l.warn(m, p)),
        ERROR((l, m, p) -> l.error(m, p));

        private Handler handler;

    }

    @FunctionalInterface
    public interface Handler {

        void process(Logger logger, String message, Object... param);

    }

}
